package com.OnTimeTeam.OnTime;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AddressAutoCompletionIO {
	
	
	public static void createAddressesfile(String filePath, boolean isFavorite){
		
        try {

        	//filePath parameter - the path of the file (on mobile it's SD card)
            
    		//create file object in the path given
    		File file = new File(filePath);
        	
    		//Only if file doesn't exist - create the labels.xml file and enter the labels node
    		if(file.createNewFile()) {
    			
	        	//Creating an empty XML Document
	
	        	//We need a Document
	        	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	        	DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	
	            ////////////////////////
	            //Creating the XML tree
	            
	            doc.normalize();
	
	            //create the root element named addresses and add it to the document
	            Element root = doc.createElement("addresses");
	            doc.appendChild(root);

	            //Enter some example default address:
	            
	            /*if(!isFavorite) {
	            
		            Element address1 = doc.createElement("address");
		            address1.setTextContent("Tel Aviv, Alexander");
		            root.appendChild(address1);
		            
	
		            Element address2 = doc.createElement("address");
		            address2.setTextContent("Ramat Gan, Sarah Aharonson");
		            root.appendChild(address2);
	            
	            }*/
	            
	            /////////////////
	            //Output the XML
	
	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");
	
	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	            String xmlString = sw.toString();
	    		
	            //Finally - write to the file the node "reminders"
    			FileWriter fStream = new FileWriter(filePath);
    			BufferedWriter out = new BufferedWriter(fStream);
	    		out.write(xmlString);
	    		
	    		//close the file
	    		out.close();
	    		
    		}//end of "if"

        }//end of try block
        catch (Exception e) {//catch any exception
            System.out.println(e);
        }
        
    }//end of method 'createAddressesfile'
	
	
	public static String[] getAllAddresses(String filePath){
		
		//init' Array List of strings (each is label)
		ArrayList<String> addressesObjects = new ArrayList<String>();
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

            //Get the root of document (reminders node)
            Element rootNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of addresses nodes
            NodeList addresses = rootNode.getChildNodes();
                      
            //In this loop we get all alarm nodes in the file
            for(int index = 0; index < addresses.getLength() ; ++index) {
            	if (addresses.item(index) instanceof Element) {//if the current item is instance of Element node
            		
        			//add the current address
        			addressesObjects.add(addresses.item(index).getTextContent());
            	}
            }//End of 'for' loop
            
        }//end of try block
        catch (Exception e) {//catch any exception
            System.out.println(e);
        }
        
		
		String[] addressesToReturn = new String[addressesObjects.size()];
		for(int i = addressesObjects.size()-1, j = 0; i >= 0; --i, ++j)
			addressesToReturn[j] = addressesObjects.get(i);
		 
		return addressesToReturn;
		
    }//end of method 'getAllAddresses'
	
	
	public static void deleteAddress(String filePath, String address) {
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            Element root = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            NodeList addressesNodes = root.getChildNodes();
            
            //search for the city
            int i;
            for(i = 0; i < addressesNodes.getLength() ; ++i){
            	if (addressesNodes.item(i) instanceof Element){
            		if(addressesNodes.item(i).getTextContent().equals(address)){
            			addressesNodes.item(i).getParentNode().removeChild(addressesNodes.item(i));
            			break;
            		}
            	}
            }
            
            doc.normalize();
            
            
            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of XML while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);

		}
		catch (Exception err) {//Catch any Exception
	    	err.printStackTrace();
	    }
	}

	
	public static void addNewAddress(String filePath, String newAddress) {
		
		deleteAddress(filePath, newAddress);
		
	    try {
	    	
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

            doc.normalize();
            
            //Get the root of document (reminders node)
            Element addresses = doc.getDocumentElement();

            //get all addresses in file
            NodeList addressesNodes = addresses.getChildNodes();
            
            //search for the city
            int i;
            for(i = 0; i < addressesNodes.getLength() ; ++i)
            	if (addressesNodes.item(i) instanceof Element)
            		if(addressesNodes.item(i).getTextContent().equals(newAddress))
            			break; //the address is already exist so break the loop
            
            if(i == addressesNodes.getLength()) { // enter new address only if it doesn't exist
            	  
        	    Element newAddressNode = doc.createElement("address");
            	newAddressNode.setTextContent(newAddress);
            	addresses.appendChild(newAddressNode);
            }
            
            /////////////////
            //Change addresses.xml file 
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of XML while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);   
            
        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
	}
	
	public static void initializeAddressesFile(String filePath){
		
		try{
			
			
	    	File previousFile = new File(filePath);
	    	previousFile.delete();
			
	    	//We need a Document
	    	DocumentBuilderFactory dbFactoryNew = DocumentBuilderFactory.newInstance();
	    	DocumentBuilder docBuilderNew = dbFactoryNew.newDocumentBuilder();
	        Document docNew = docBuilderNew.newDocument();
	    	
	    	
	        File newFile = new File(filePath);
	        if(newFile.createNewFile()) {
		        	
		 
		    	//We need a Document
		
		        ////////////////////////
		        //Creating the XML tree
		        
		    	docNew.normalize();
		
		        //create the root element named Reminders and add it to the document
		        Element root = docNew.createElement("addresses");
		        docNew.appendChild(root);
		
	            Element address1 = docNew.createElement("address");
	            address1.setTextContent("Tel Aviv, Alexander");
	            root.appendChild(address1);
	            

	            Element address2 = docNew.createElement("address");
	            address2.setTextContent("Ramat Gan, Sarah Aharonson");
	            root.appendChild(address2);
		        
		        /////////////////
		        //Output the XML
		
		        //set up a transformer
		        TransformerFactory transfac = TransformerFactory.newInstance();
		        Transformer trans = transfac.newTransformer();
		        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		        trans.setOutputProperty(OutputKeys.INDENT, "yes");
		
		        //create string from xml tree
		        StringWriter sw = new StringWriter();
		        StreamResult result = new StreamResult(sw);
		        DOMSource source = new DOMSource(docNew);
		        trans.transform(source, result);
		        String xmlString = sw.toString();
				
		        //Finally - write to the file the node "reminders"
				FileWriter fStream = new FileWriter(filePath);
				BufferedWriter out = new BufferedWriter(fStream);
				out.write(xmlString);
				
				//close the file
				out.close();	
	        }
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
